package org.chunchu.todo.mvp.impl;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Singleton;

import org.chunchu.todo.AddTaskActivity;
import org.chunchu.todo.Main;
import org.chunchu.todo.dao.TaskDao;
import org.chunchu.todo.model.Category;
import org.chunchu.todo.model.Task;
import org.mvp.AbstractPresenter;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

@Singleton
public class TaskListPresenter extends AbstractPresenter<TaskList> {

	private int lastPositionSelected;
	@Inject
	private TaskDao taskDao;
	@Inject
	private Activity main;
	@Inject
	private CategoryListPresenter categoryPresenter;
	@Inject
	private TaskPresenter taskPresenter;

	@Override
	public void initializeWith(TaskList activity) {
		super.initializeWith(activity);
		activity.setTasks(taskDao.findAll());
	}

	public void setCurrentCategory(Category category) {
		List<Task> taskList = taskDao.findByCategoryId(category.getId());
		getActivity().setTasks(taskList);
		changePosition(0);
	}

	public void changePosition(int position) {
		Task task = getActivity().getTaskAt(position);
		lastPositionSelected = position;
		taskPresenter.setCurrentTask(task);
	}

	public void removeItem(int position) {
		Task task = getActivity().getTaskAt(position);
		taskDao.remove(task.getId());
		getActivity().getTasks().remove(position);
		getActivity().updateUi();
		if (lastPositionSelected == position) {
			taskPresenter.cleanTask();
		}
	}

	public void editItem(int position) {
		Bundle bundle = new Bundle();
		Task task = getActivity().getTaskAt(position);
		bundle.putSerializable(AddTask.EXTRA_TASK, task);
		Intent intent = new Intent(main, AddTaskActivity.class);
		intent.putExtras(bundle);
		intent.setAction(Main.ACTION_EDIT);
		main.startActivity(intent);
	}

	public void addItem() {
		Bundle bundle = new Bundle();
		long id = categoryPresenter.getCurrentPositionId();
		Task task = new Task("", "", id);
		bundle.putSerializable(AddTask.EXTRA_TASK, task);
		Intent intent = new Intent(main, AddTaskActivity.class);
		intent.putExtras(bundle);
		intent.setAction(Main.ACTION_ADD);
		main.startActivity(intent);
	}

}
